//
//  LoginDelegate.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/1/11.
//

import Foundation
import SwiftUI

//日记委托类
class DiaryDelegate<T: DiaryProtocol>: DiaryProtocol {
    
    private let instance : T
    
    init(instance: T) {
        self.instance = instance
    }
    
    private var listTag: [TagBean]? = nil //标签列表
    var initTag = false //标签是否初始化了
    
    
    //处理标签，因为日记列表返回只有一个标签id，所以需要遍历处理
    private func dealTag(_ list: [DiaryBean]) async throws {
        if !initTag {
            listTag = try await BackupsManager.shared.getDelegateConfig()?.getTagList()
        }
        list.forEach{ diary in
            //存在标签，则处理
            if !(diary.tagId ?? "").isEmpty {
                var modify = false
                let tagBean = listTag?.first{ tag in tag.objectId == diary.tagId}
                if (tagBean == nil) {
                    //标签已经被删除了
                    diary.tagId = nil
                    diary.tagName = nil
                    modify = true
                } else if (diary.tagName != tagBean?.text) {
                    //标签名字已经被该
                    if (diary.tagName != nil) {
                        //标签名字已经被该
                        modify = true
                    }
                    diary.tagName = tagBean?.text
                }
                if (modify) {
                    //更改处理
                    //saveDiary(it)
                }
            }
        }
    }
    
    func queryHomeDiary(userId: String, startTime: Int64, endTime: Int64, keyword: String?, pageNo: Int, pageSize: Int) async throws -> [DiaryBean] {
        showLog("开始时间：\(TimeUtils.getDate(time: startTime, format: "yyyy-MM-dd HH:mm:ss"))")
        showLog("结束时间：\(TimeUtils.getDate(time: endTime, format: "yyyy-MM-dd HH:mm:ss"))")
        let list =  try await instance.queryHomeDiary(userId:userId,startTime:startTime, endTime: endTime, keyword: keyword, pageNo:pageNo, pageSize:pageSize)
        try await dealTag(list)
        try await DiaryExt.dealPicture(list, true)
        try await DiaryExt.dealComment(list)
        return list
    }
    
    
    func queryDiaryAi(userId:String, roleId:String, keyword:String?, pageNo:Int, pageSize:Int) async throws -> [DiaryBean] {
        let list =  try await instance.queryDiaryAi(userId:userId, roleId: roleId, keyword: keyword, pageNo:pageNo, pageSize:pageSize)
        try await dealTag(list)
        try await DiaryExt.dealPicture(list, true)
        try await DiaryExt.dealComment(list)
        return list
    }
    
    func queryStatisticsDiary(userId: String, curTime: TimeInterval, endTime: TimeInterval, isPicture: Bool) async throws -> [DiaryBean] {
        //curTime是月末，，endTime是月初，是倒着过来的
        showLog("指定时间：\(TimeUtils.getDate(time: curTime, format: "yyyy-MM-dd HH:mm:ss"))")
        showLog("结束时间：\(TimeUtils.getDate(time: endTime, format: "yyyy-MM-dd HH:mm:ss"))")
        let list =  try await instance.queryStatisticsDiary(userId:userId, curTime: curTime, endTime: endTime,isPicture: isPicture)
        if isPicture {
            try await DiaryExt.dealPicture(list, true)
        }
        return list
    }
    
    func queryDiaryLately(userId: String, pageNo: Int, pageSize: Int) async throws -> [DiaryBean] {
        return try await instance.queryDiaryLately(userId: userId, pageNo: pageNo, pageSize: pageSize)
    }
    
    func queryDiaryUpdateAll(userId: String, pageNo: Int, pageSize: Int) async throws -> [DiaryBean] {
        return try await instance.queryDiaryUpdateAll(userId: userId, pageNo: pageNo, pageSize: pageSize)
    }
    
    func queryTag(userId: String, tagId: String?, pageNo: Int, pageSize: Int) async throws -> [DiaryBean] {
        let list = try await instance.queryTag(userId: userId, tagId: tagId, pageNo: pageNo, pageSize: pageSize)
        try await dealTag(list)
        try await DiaryExt.dealPicture(list, true)
        try await DiaryExt.dealComment(list)
        return list
    }
    
    func queryMemoryDiary(aiUserId: String?, userId: String, pageNo: Int, pageSize: Int) async throws -> [DiaryBean] {
        return try await instance.queryMemoryDiary(aiUserId: aiUserId, userId: userId, pageNo: pageNo, pageSize: pageSize)
    }
    
    func saveDiary(bean: DiaryBean) async throws  {
        try await instance.saveDiary(bean: bean)
    }
    
    func delDiary(bean: DiaryBean) async throws {
        try await instance.delDiary(bean: bean)
    }
    
    func saveCloudPicture(bean: CloudPictureBean) async throws {
        try await instance.saveCloudPicture(bean: bean)
    }
    
    func delCloudPicture(bean: CloudPictureBean) async throws {
        try await instance.delCloudPicture(bean: bean)
    }
    
    func queryPicture(diaryId: String, userId: String, limit: Int) async throws -> [CloudPictureBean] {
        return try await instance.queryPicture(diaryId: diaryId, userId: userId, limit: limit)
    }
    
    func queryDiaryComment(diaryId: String, pageNo: Int, pageSize: Int) async throws -> [DiaryCommentBean] {
        return try await instance.queryDiaryComment(diaryId: diaryId, pageNo: pageNo, pageSize: pageSize)
    }
    
    
    func queryDiaryComment(diaryId: String, aiRoleId: String, pageNo: Int, pageSize: Int) async throws -> [DiaryCommentBean] {
        return try await instance.queryDiaryComment(diaryId: diaryId, aiRoleId:aiRoleId, pageNo: pageNo, pageSize: pageSize)
    }
    
    
    func queryDiaryLast(diaryId: String, aiRoleId: String) async throws -> DiaryCommentBean? {
        return try await instance.queryDiaryLast(diaryId: diaryId, aiRoleId:aiRoleId)
    }
    
    func addDiaryComment(bean: DiaryCommentBean) async throws -> DiaryCommentBean? {
        return try await instance.addDiaryComment(bean: bean)
    }
    
    func deleteDiaryComment(bean: DiaryCommentBean) async throws {
        try await instance.deleteDiaryComment(bean: bean)
    }
    
    func queryWeekLetter(userId: String, pageNo: Int, pageSize: Int) async throws -> [WeeklyLetterBean] {
        try await instance.queryWeekLetter(userId: userId, pageNo: pageNo, pageSize: pageSize)
    }
    
    func updateLastWeekLetter(bean: WeeklyLetterBean) async throws -> WeeklyLetterBean {
        return try await instance.updateLastWeekLetter(bean:bean)
    }
    
    func deleteLastWeekLetter(bean: WeeklyLetterBean) async throws {
        try await instance.deleteLastWeekLetter(bean:bean)
    }
    
    func queryActiveCall(userId: String, pageNo: Int, pageSize: Int) async throws -> [CallHistoryBean] {
        try await instance.queryActiveCall(userId: userId, pageNo: pageNo, pageSize: pageSize)
    }
    
    func deleteActiveCall(bean: CallHistoryBean) async throws {
        try await instance.deleteActiveCall(bean:bean)
    }
    
    func updateActiveCall(bean: CallHistoryBean) async throws {
        try await instance.updateActiveCall(bean:bean)
    }
    
    func existTask(timeKey: String, roleId: String?, userId: String, type: Int) async throws -> Bool {
        return try await instance.existTask(timeKey: timeKey, roleId: roleId, userId: userId, type: type)
    }
    
    func saveTask(bean: TaskBean) async throws -> TaskBean? {
        return try await instance.saveTask(bean: bean)
    }
    func getLatelyTask(roleId: String?, userId: String, type: Int, pageSize: Int) async throws -> [TaskBean] {
        return try await instance.getLatelyTask(roleId: roleId, userId: userId, type: type, pageSize: pageSize)
    }
    func getUnExecutedTask(roleId: String?, userId: String, type: Int?) async throws -> [TaskBean] {
        return try await instance.getUnExecutedTask(roleId: roleId, userId: userId, type: type)
    }
    
    func deleteTask(bean: TaskBean) async throws {
        try await instance.deleteTask(bean: bean)
        //删除完成后，需要删除服务器的推送
        try await retry(maxRetries: 10, retryDelayMillis: 500) {
            try await PushExt.deleteSchedule(msgId: bean.objectId ?? "")
        }
    }
    
    func queryChat(objectId: String) async throws -> ChatBean? {
        return try await instance.queryChat(objectId: objectId)
    }
    
    func queryChat(pageNo: Int, pageSize: Int) async throws -> [ChatBean] {
        return try await instance.queryChat(pageNo: pageNo, pageSize: pageSize)
    }
    
    func queryChat(aiUserId: String, userId: String, pageNo: Int, pageSize: Int) async throws -> [ChatBean] {
        return try await instance.queryChat(aiUserId: aiUserId, userId: userId, pageNo: pageNo, pageSize: pageSize)
    }
    
    func queryChat(aiUserId: String, userId: String, isRefresh: Bool, timestamp: Int64, pageSize: Int) async throws -> [ChatBean] {
        return try await instance.queryChat(aiUserId: aiUserId, userId: userId, isRefresh: isRefresh, timestamp: timestamp, pageSize: pageSize)
    }
    
    func queryNewChat(aiUserId: String, userId: String) async throws -> ChatBean? {
        return try await instance.queryNewChat(aiUserId: aiUserId, userId: userId)
    }
    
    func queryMemoryChat(aiUserId: String, userId: String, pageNo: Int, pageSize: Int) async throws -> [ChatBean] {
        return try await instance.queryMemoryChat(aiUserId: aiUserId, userId: userId, pageNo: pageNo, pageSize: pageSize)
    }
    
    func addChat(bean: ChatBean) async throws -> ChatBean {
         try await instance.addChat(bean: bean)
    }
    
    func saveChat(bean: ChatBean) async throws {
        try await instance.saveChat(bean: bean)
    }
    
    func saveChat(list: [ChatBean]) async throws {
        try await instance.saveChat(list: list)
    }
    
    func clearChat(aiUserId: String, userId: String) async throws {
        try await instance.clearChat(aiUserId: aiUserId, userId: userId)
    }
    
    func deleteChat(bean: ChatBean) async throws {
        try await instance.deleteChat(bean: bean)
    }
    
    func deleteChatList(beans: [ChatBean]) async throws {
        try await instance.deleteChatList(beans: beans)
    }
    
    func getEmojiPictureList() async throws -> [EmojiPictureBean] {
        try await instance.getEmojiPictureList()
    }
    
    func addEmojiPicture(bean: EmojiPictureBean) async throws -> EmojiPictureBean {
        try await instance.addEmojiPicture(bean: bean)
    }
    
    func saveEmojiPicture(bean: EmojiPictureBean) async throws {
        try await instance.saveEmojiPicture(bean: bean)
    }
    
    func deleteEmojiPicture(bean: EmojiPictureBean) async throws {
        try await instance.deleteEmojiPicture(bean: bean)
    }
    
    func queryNewChatMemory(aiRoleId: String, userId: String) async throws -> [AiMemoryBean] {
        try await instance.queryNewChatMemory(aiRoleId: aiRoleId, userId: userId)
    }
    
    func queryMyNewChatMemory(userId: String) async throws -> [AiMemoryBean] {
        try await instance.queryMyNewChatMemory(userId: userId)
    }
    
    func addMemory(bean: AiMemoryBean) async throws {
        try await instance.addMemory(bean: bean)
    }
    
}
